package cn.smart.epic.core.aop;

import cn.smart.epic.common.annotion.Permission;
import cn.smart.epic.core.shiro.check.PermissionCheckManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.naming.NoPermissionException;
import java.lang.reflect.Method;

/**
 * @Auther Z.B
 * @date 2017/10/11 10:47
 * @Email 2545375@qq.com
 * @Description AOP 权限自定义检查
 * @since 1.0
 */

@Aspect
@Component
public class PermissionAop {
    @Pointcut(value = "@annotation(cn.smart.epic.common.annotion.Permission)")
    private void cutPermission() {

    }

    @Around("cutPermission()")
    public Object doPermission(ProceedingJoinPoint point)throws Throwable {
        MethodSignature signature =(MethodSignature) point.getSignature();
        Method method =signature.getMethod();
        Permission permission=method.getAnnotation(Permission.class);
        Object[] permissions = permission.value();
        if (permissions == null || permissions.length==0) {
            boolean result = PermissionCheckManager.checkAll();
            if (result) {
               return point.proceed();
            }else{
                throw new NoPermissionException();
            }
        }else{
            boolean result = PermissionCheckManager.check(permissions);
            if (result) {
                return point.proceed();
            }else{
                throw new NoPermissionException();
            }
        }
    }
}
